<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        /**
         *  WebStorage是html5中引入的本地存储解决方案，可以在客户端本地存储数据
         *  由两部分组成：
         *  localStorage：在本地永久性存储数据
         *  sessionStorage：存储的数据只在会话期间有效，关闭浏览器则自动删除
         */

        /**
         *  localStorage和sessionStorage的用法相同，常用API 
         */

        /**
         *  setItem(key,value):写入数据，添加或修改 键值对 
         *  getItem(key):读取数据，根据键对应的值
         *  removeItem(key):删除数据，根据键删除对应的键值对
         *  key(index):根据索引获取对应的键 
         *  clear():清空数据 
         *  length:获取键值对数量 
         */
        function readdStorage() {
            console.log(localStorage.getItem("name"));
            console.log(sessionStorage.getItem("name"));
            console.log(JSON.parse(localStorage.getItem('stu')))
            console.log(JSON.parse(localStorage.getItem('province'))[1].id);
            
        }
        function removeStorage() {
            localStorage.removeItem('age')
        }
        function doStorage() {
            // console.log(localStorage.key(2))
            // console.log(localStorage.key(0))

            // localStorage.clear();

            // console.log(localStorage.length);
        }

        /**
         *  WebStorage中只能存储字符串数据，如果要存储对象，需要先转化为字符串形式
         */
        var stu = new Object
        stu.name = '高伟杰'
        stu.age = 18

        var province = [
            {
                id: 1001,
                name: '兴城',
                age: 888
            },
            {
                id: 1002,
                name: '北京',
                age: 999
            },
            {
                id: 1003,
                name: '上海',
                age: 555
            },
        ]

        function writeStorage() {
            localStorage.setItem('name', 'tom')
            localStorage.setItem('age', 18)
            localStorage.setItem('sex', 'male')
            localStorage.setItem('stu', JSON.stringify(stu))
            localStorage.setItem('province',JSON.stringify(province))
            sessionStorage.setItem('name', 'tom')
        }
    </script>
</head>

<body>
    <button onclick="writeStorage()">写入WebStorage</button>
    <button onclick="readdStorage()">读取WebStorage</button>
    <button onclick="removeStorage()">删除WebStorage</button>
    <button onclick="doStorage()">操作WebStorage</button>
</body>

</html>